package com.alan.netty.rpc.v1;

import com.alan.netty.rpc.common.RpcRequest;
import com.alan.netty.rpc.common.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author weiBin
 * @date 2018/11/27
 */
@Slf4j
public class RpcServerHandler extends SimpleChannelInboundHandler<RpcRequest> {
    private RpcBuilder builder;

    public RpcServerHandler(RpcBuilder builder) {
        this.builder = builder;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequest request) throws Exception {
        //调用具体的业务方法，调用 CalculatorService.add方法
        RpcResponse response = builder.invokeService(request);
        // 把响应返回给客户端
        ctx.writeAndFlush(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("远程连接异常：", cause);
        ctx.close();
    }
}
